package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"yzy6.26exam/api/request"
	"yzy6.26exam/golbal"
	"yzy6.26exam/internal/bao"
	"yzy6.26exam/internal/moble"
	"yzy6.26exam/pkg"
)

func Login(context *gin.Context) {
	var login request.Login
	if err := context.ShouldBind(&login); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    204,
			"message": "解析失败",
			"data":    err.Error(),
		})
		return
	}
	var user moble.User
	user.Mobile = login.Mobile
	if err := bao.FindOnce(&user); err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    203,
			"message": "登录失败",
			"data":    err.Error(),
		})
		return
	}
	if user.ID == 0 || pkg.Md5(login.Password) != user.Password {
		context.JSON(http.StatusOK, gin.H{
			"code":    202,
			"message": "账号或密码错误",
		})
		return
	}
	get, err := pkg.TokenGet(user.ID)
	if err != nil {
		context.JSON(http.StatusOK, gin.H{
			"code":    201,
			"message": "登录失败",
			"data":    err.Error(),
		})
		return
	}
	golbal.RDB.Set(golbal.Ctx, fmt.Sprintf("user:token:%s", get), user.ID, 24*time.Hour)
	context.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data":    get,
	})
	return
}
